<template>
    <div class="progress" :style="obj">
    </div>
</template>

<script setup>
let obj = reactive({
    width: '0%'
})

onMounted(() => {
    // 节流
    const throttle = (func, wait, mustRun) => {
        var timeout,
            startTime = new Date();

        return function () {
            var context = this,
                args = arguments,
                curTime = new Date();

            clearTimeout(timeout);
            // 如果达到了规定的触发时间间隔，触发 handler
            if (curTime - startTime >= mustRun) {
                func.apply(context, args);
                startTime = curTime;
                // 没达到触发间隔，重新设定定时器
            } else {
                timeout = setTimeout(func, wait);
            }
        };
    };

    const progress = () => {
        let width = (document.documentElement.scrollTop + window.innerHeight) * 100 / document.body.offsetHeight
        if (document.documentElement.scrollTop == 0) {
            width = 0
        }
        obj.width = `${width}%`
    }

    window.addEventListener('scroll', throttle(progress, 200, 400));
})
</script>

<style scoped>
.progress {
    border-radius: 5px;
    position: fixed;
    z-index: 10;
    top: 58px;
    height: 4px;
    transition: .7s;
    background: linear-gradient(-60deg, #ff5858 0%, #f09819 100%);
}
</style>
